<template>
  <div>
    <div class="headBtns">
          <el-button-group style="margin-right:20px">
            <el-button size="small" icon="el-icon-plus" @click="add">添加行事历</el-button>
            <!-- <el-button size="small" icon="el-icon-edit">修改</el-button> -->
            <el-button size="small" icon="el-icon-edit"  @click="importFile">行事历导入</el-button>
            <el-button size="small" icon="el-icon-close" @click="statusListAct" style='color:red'>批量停用</el-button>
          </el-button-group>
          <span class="search_label">用 户 名</span>
          <el-input
          size="small"
          style="width:180px"
          placeholder="请输入关键字"
          suffix-icon="el-icon-search"
          v-model="keywords">
          </el-input>

    </div>
    <div class="w_list">
       <el-table ref="multipleTable" :data="tableData" tooltip-effect="dark" style="width: 100%"
          @selection-change="handleSelectionChange">
        <el-table-column align="center" type="selection" width="40"></el-table-column>
        <el-table-column align="center" prop="name" label="行事历名称" width="120"></el-table-column>
        <el-table-column align="center" prop="content" show-overflow-tooltip label="行事历内容" width="120"></el-table-column>
        <el-table-column align="center" prop="type" :formatter="labelTyle" label="行事历类型" ></el-table-column>
        <el-table-column align="center" prop="userName" label="姓名"></el-table-column>
        <el-table-column align="center" prop="orgName" label="所属组织"></el-table-column>
        <el-table-column align="center" prop="stationName" label="岗位属性" ></el-table-column>
        <el-table-column align="center" label="生效时间" prop="workDate" width="120">
        </el-table-column>
        <!-- <el-table-column align="center" prop="zhuangtai" label="状态" :formatter="Form_zhuangtai"></el-table-column> -->
        <el-table-column
                    label="状态"
                    align="center">
                      <template slot-scope="scope">
                       <el-button 
                        :type="scope.row.status == 'n' ? 'info' : 'success'" 
                        size="small" 
                        @click="statusReset(scope.row)">{{scope.row.status == 'n' ? '冻结' : '启用'}}</el-button>
                    </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="120">
          <template slot-scope="scope">
            <el-button type="text" @click="edit(scope.row)">编辑</el-button>
            <el-button type="text" @click="delectA(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pager ref="pager"  v-on:listenPagerEvent="getPagerData" :requestUrl="requestUrl" :requestParams="requestParams"></pager>

    </div>


    <!-- 文件下载、上传 -->
    <el-dialog title="行事历导入" :visible.sync="dialogFile">
      <ul class="fileUpload">
        <li><span>导入模板文件下载：</span><span> <el-button type="danger" style='width:240px' size="small" @click="downloadFile">点击下载导入模板文件</el-button></span></li>
        <li><span>行事历清单：</span><span style="position:relative">
           <el-input id="batchImport" name="batchImport" style="width:240px;height:20px;" v-model="fileName" size="small" readonly placeholder="请选择（仅支持.xls/.xlsx格式文件）"></el-input>
           <el-upload style="display:inline-block;position:absolute;left:260px;height:30px" 
            id="batchImport" 
            name="batchImport"
            ref="upload"
            :action="importUrl"
            accept='.xls,.xlsx'
            :multiple="false"
            :limit=1
            :show-file-list="false"
            :before-upload="beforeLoad"
            :on-success="successRes"
            :on-error="errorRes"
            :auto-upload="false"
            :data="formData"
            :on-change="fileChecked"
            :on-progress="isUpdata"
            :headers="headerToken"
           >
            <el-button size="small" type="danger">选择文件</el-button>
           </el-upload>
          </span></li>
      </ul>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFile = false">取 消</el-button>
        <el-button type="primary" @click="submitLoadFile">导 入</el-button>
      </div>
    </el-dialog>

    <!-- 添加和编辑的弹窗 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible">
      <el-form :model="upDataForm">
        <el-form-item label="人员所属组织名称" label-width="150px">
          <el-autocomplete
                size="mini"
                v-model="upDataForm.pName"
                :fetch-suggestions="searchOrg"
                placeholder="请输入组织名称（必填）"
                @select="handleSelectOrg"
                :trigger-on-focus="false"
                value-key="name"
        ></el-autocomplete>
        </el-form-item>
        <el-form-item label="人员信息" label-width="150px">
          <el-select @change="personSelect" size="mini" filterable v-model="upDataForm.userName" placeholder="请选择人员"  style="width:100%" >
            <el-option
              v-for="item in options"
              :label="item.userName"
              :value="item.userId"
              :key="item.userId"
              >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="行事历名称" label-width="150px" style="width:50%;float:left">
           <el-input size="mini" v-model="upDataForm.name" placeholder="请输入行事历名称" ></el-input>
        </el-form-item>
        <el-form-item label="行事历类型" label-width="120px" style="width:50%;float:left">
          <el-select size="mini" v-model="upDataForm.type" @change="timerType" placeholder="请选择行事历类型" style="width:100%;"
                  >
            <el-option label="周事历" value="week"></el-option>
            <el-option label="月事历" value="month"></el-option>
            <el-option label="季事历" value="quarter"></el-option>
            <el-option label="半年事历" value="halfyear"></el-option>
            <el-option label="年事历" value="year"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="行事历内容" label-width="150px" class="cf">
          <el-input type="textarea" :rows="3" placeholder="请输入行事历内容（限200字）" v-model="upDataForm.content"
             
          ></el-input>
        </el-form-item>
        <el-form-item label="生效时间" label-width="150px">
          <el-select size="mini" v-model="upDataForm.workDate" @change="creatTimer" placeholder="生效时间" style="width:100%" >
            <el-option label="立即生效" value="1"></el-option>
            <el-option label="次年生效" value="2"></el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="dialogVisible = false">取 消</el-button>
        <el-button size="mini" type="primary" @click="addClick">{{dialogTitle == '编辑行事历' ? '保存' : '添加'}}</el-button>
      </div>
    </el-dialog>
    
  </div>
</template>



<script>

import {Loading} from 'element-ui'
import {taskPlanWebList,batchImport,planAdd,findOrgList,findPageList,doStatus,startOrStop,doDelete} from '../../tool/config'
import pager from '../common/pager.vue'
import { Notification } from 'element-ui'

export default {
    components:{pager},
    data() {
      return {
        dialogVisible:false,  //添加弹出框状态
        dialogFile:false,     //行事历导入弹出框状态
        upDataForm:{       //添加行事历的表单
          content:'',
          name:'',
          orgId:'',
          pName:'',
          stationId:'',
          property:'',
          type:'week',
          userId:'',
          workDate:'1',
          userName:'',
          id:'',//此行事历的id
        },
        tableData:[],//表格数据
        multipleSelection: [],  //批量选择操作
        keywords:'',//搜索关键词
        dialogTitle:'',//弹框的标题
        fileName: '', //文件名称
        formData:{},  //文件导入的其他参数
        importUrl:'',//导入地址
        headerToken:{},
        orgNameString:[],//组织名称列表
        options:[],//人员选择
        //行事历分页
        requestParams:{
        orgId:'',
        keywords:'',
        stationId:'',
        reload:Number
        },
        requestUrl:taskPlanWebList,
        formList:[],
      }
    },
    mounted(){
      this.importUrl = batchImport();
      this.headerToken = {
        token:localStorage['token']
      }
    },
    methods: {
      
      //分页获取数据
      getPagerData(data,pageSize,pageNum){
          this.tableData = data;
      },
      //停用或启用
      statusReset(row){
        const title = row.status == 'y' ? '账号冻结' : '账号启用';
        const content = row.status == 'y' ? '账号冻结后将无法正常登录APP，确认冻结该人员账号吗？' : '确认启用该人员账号吗？';
        this.$confirm(content, title, {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            startOrStop({id:row.id}).then(res=>{
              if(res.code == 0){
                this.requestParams.reload = Math.random();//重载
                this.$message({
                type: 'success',
                message: '操作成功!'
                });
              }else{
                this.$message({
                type: 'warning',
                message: res.msg
                });
              }
            })
          }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消操作'
          });
        });
      },
      labelTyle(row,column){
        const type = row.type;
        return type == 'week' ? '周行事历' :type == 'month' ? '月行事历' : type == 'quarter' ? '季度行事历' : type == 'halfyear' ? '半年行事历' : type == 'year' ? '年行事历' : '';
      },
      //弹框选择组织
      handleSelectOrg(item){
        this.upDataForm.orgId = item.id;
      },
      searchOrg(string,cb){
      //返回可选列表
        cb(this.orgNameString);
      },
      // 人员选择
      personSelect(userId){
        let obj = {};
        obj = this.options.find((item)=>{
            return item.userId === userId;//筛选出匹配数据
        });
        this.upDataForm.stationId = obj.stationId;
        this.upDataForm.userId = obj.userId;
      },
      //行事历选择
      timerType(val){
        this.upDataForm.type = val;
      },
      creatTimer(val){
        let myDate = new Date();
        let workDate = myDate.getFullYear();
        // 传实际年份给后台
        if(val == '1'){
          this.upDataForm.workDate = workDate;
        }else{
          this.upDataForm.workDate = workDate + 1;
        }
      },
      statusListAct(){
        if(this.multipleSelection.length == 0){
          this.$notify({
          title: '提示',
          message: '请至少选择一条数据',
          duration: 3000,
          type: 'warning'
          });
          return
        }else{
          this.dialogTitle = '添加行事历';
          this.$confirm('确认批量停用或启用行事历吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let str = "";
          for (var val of this.multipleSelection) {
            str += val.id;
            str += ',';
          }
          doStatus({ids:str}).then(res=>{
            if(res.code == 0){
              this.requestParams.reload = Math.random();//刷新数据
              this.$message({
              type: 'success',
              message: '操作成功!'
              });
            }else{
              this.$notify({
                title: '提示',
                message: res.msg,
                duration: 3000,
                type: 'warning'
              });
            }
          })
          
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
        }
      },
      // 添加批量操作
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },
      add(){
        this.dialogTitle = '添加行事历';
        this.dialogVisible = true;
        //清空表格回显
        this.upDataForm = {
          content:'',
          name:'',
          orgId:'',
          pName:'',
          stationId:'',
          property:'',
          type:'week',
          userId:'',
          workDate:'1',
          userName:''
        }
      },
      edit(row){
        this.dialogTitle = '编辑行事历';
        this.dialogVisible = true;
        console.log(row)
        //回显
        this.upDataForm = {
          content:row.content,
          name:row.name,
          orgId:row.orgId,
          pName:row.orgName,
          stationId:row.stationId,
          property:row.stationName,
          type:row.type,
          userId:row.userId,
          workDate:'1',
          userName:row.userName,
          id:row.id
        }
      },

      //确认添加或编辑
      addClick(){
        // self.dialogVisible = false;
        if(!this.upDataForm.orgId){
          this.$notify({
          title: '提示',
          message: '请选择组织名称',
          duration: 3000,
          type: 'warning'
          });
          return
        }
        if(!this.upDataForm.name){
          this.$notify({
          title: '提示',
          message: '请输入行事历名称',
          duration: 3000,
          type: 'warning'
          });
          return
        }
        if(!this.upDataForm.content){
          this.$notify({
          title: '提示',
          message: '请输入行事历内容',
          duration: 3000,
          type: 'warning'
          });
          return
        }
        if(!this.upDataForm.userId){
          this.$notify({
          title: '提示',
          message: '请选择人员',
          duration: 3000,
          type: 'warning'
          });
          return
        }
        var obj = {};
        //编辑
        if(this.dialogTitle == '编辑行事历'){
          obj = {
            content:this.upDataForm.content,
            name:this.upDataForm.name,
            orgId:this.upDataForm.orgId,
            stationId:this.upDataForm.stationId,
            workDate:this.upDataForm.workDate,
            type:this.upDataForm.type,
            userId:this.upDataForm.userId,
            id:this.upDataForm.id
          }
        // 添加
        }else{
        //数据传递给后台
          obj ={
            content:this.upDataForm.content,
            name:this.upDataForm.name,
            orgId:this.upDataForm.orgId,
            stationId:this.upDataForm.stationId,
            workDate:this.upDataForm.workDate,
            type:this.upDataForm.type,
            userId:this.upDataForm.userId
          }
        }
          planAdd(obj).then(res=>{
            if(res.code == 0){
              this.dialogVisible = false;
              this.requestParams.reload = Math.random();
              this.$notify({
                title: '提示',
                message: this.dialogTitle == '编辑行事历' ? '修改成功' : '添加成功',
                duration: 3000,
                type: 'success'
              });
            }else{
              this.$notify({
                title: '提示',
                message: res.msg,
                duration: 3000,
                type: 'success'
              });
            }
          })
      },

      //下载模板文件
      downloadFile(){
        window.location.href = '../../../static/tmpFile/batchImport.xlsx'
      },

      //导入
      importFile(){
        let self = this;
        self.dialogFile = true;
      },
      //选择文件后
      fileChecked(file,fileList){
        if(fileList.length > 1){
          fileList.splice(0,1)
        };
        this.fileName = file.name;
      },
      //上传之前的校验
      beforeLoad(file){
        const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
          || file.type === 'application/vnd.ms-excel';
        const isLt5M = file.size / 1024 / 1024 < 5;
        if(!isExcel){
          this.$alert('上传文件必须为excel格式', '提示', {
            type:'info',
            confirmButtonText: '确定',
            showClose:false}).then(function(){return });
        };
        if(!isLt5M){
          this.$alert('上传文件大小不能超过5M', '提示', {
            type:'info',
            confirmButtonText: '确定',
            showClose:false}).then(function(){return});
        }
        return isExcel && isLt5M ;
      },
      //确认导入
      submitLoadFile(){
        this.$refs.upload.submit();
      },
      //上传成功
      successRes(res){
        this.dataUp.close();
        if(res.code == 0){
          this.dialogFile = false;
        }
        this.$notify({
            title: '提示',
            message: res.msg,
            duration: 3000,
            type: 'success'
          });
      },
      //上传失败
      errorRes(res){
        console.log(res)
        this.dataUp.close();
        this.$notify({
          title: '提示',
          message: res.msg,
          duration: 3000,
          type: 'warning'
        });
      },
      //上传加载loading
      isUpdata(event,file){
        this.dataUp = Loading.service({fullscreen:true})
      },

      //删除
      delectA(row){
        this.$confirm('系统将一并删除与本行事历相关的所有任务，请谨慎操作。确认删除吗', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          doDelete({ids:row.id}).then(res=>{
            if(res.code == 0){
              this.requestParams.reload = Math.random();//刷新数据
              this.$message({
              type: 'success',
              message: '操作成功!'
              });
            }else{
              this.$notify({
                title: '提示',
                message: res.msg,
                duration: 3000,
                type: 'warning'
              });
            }
          })
          
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
      },

    },
    watch:{
      'upDataForm.pName':function(val,oldVal){
          val = val || '';
          findOrgList({name:val}).then((res)=>{
          if(res.code == 0){
            this.orgNameString = res.response; 
          }else{
            this.orgNameString = [];
          }
        })
      },
      'upDataForm.orgId':function(val,oldVal){
        if(val == ''){
          this.options = [];
        }else{
            if(val != oldVal && val){
            findPageList({orgId:val}).then(res=>{
              if(res.response.searchData){
                this.options = res.response.searchData;
              }else{
                
              }
            })
          }
        }
      },
      keywords(val,oldVal){
        this.requestParams.keywords = val;
      }
    }
  }

</script>


<style scoped>
  .headBtns{
    width: 100%;
    height: 50px;
    line-height: 48px;
    /* border: 1px solid #FF5656; */
    padding: 0 10px;
    background:#fff
  }
  .w_list{
    margin-top: 25px;
    /* border: 1px solid #FF5656 */
  }


  .cf::before{
    display: block;
    clear: both;
    content: ""
  }


  .fileUpload li{
    height: 46px;
  }
  .fileUpload li>span:first-child{
    display:inline-block;
    width: 130px;
    text-align: right;
  }



  /*  */
  .search_label{
    font-size: 12px
  }
  .headBtns .el-date-editor--daterange.el-input__inner{
    width: 240px
  }

</style>